﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Three.BookStore.RBAC;
using Three.BookStore.LoginERP;
using System.Linq;
using System.Collections.Generic;
using System.Text.Json;

namespace Three.BookStore.Web.Control.RBAC
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class RoleController : Controller
    {
        private readonly IRoles _roles;

        public RoleController(IRoles roles)
        {
            _roles = roles;
        }

        [HttpGet]
        [Route("/RBAC/RoleView")]
        public IActionResult RoleView()
        {
            return View("~/Views/Role/Role.cshtml");
        }

        [HttpGet]
        [Route("/RBAC/GetRoles")]
        public async Task<IActionResult> GetRoles([FromQuery] string roleName = "", [FromQuery] int page = 1, [FromQuery] int limit = 10)
        {
            try
            {
                System.Console.WriteLine("==================== 开始处理获取角色列表请求 ====================");
                System.Console.WriteLine($"请求参数 - 页码: {page}, 每页条数: {limit}, 角色名称: {roleName}");
                
                // 获取所有角色
                var roles = await _roles.GetListAsync();
                System.Console.WriteLine($"从数据库获取角色列表 - 总记录数: {roles?.Count ?? 0}");

                if (roles == null)
                {
                    System.Console.WriteLine("警告：从数据库获取的角色列表为 null");
                    return Json(new
                    {
                        code = 0,
                        msg = "",
                        count = 0,
                        data = new List<object>()
                    });
                }

                // 如果有搜索条件，进行过滤
                if (!string.IsNullOrEmpty(roleName))
                {
                    roles = roles.FindAll(r => r.RoleName.Contains(roleName));
                    System.Console.WriteLine($"按名称 '{roleName}' 过滤后的记录数: {roles.Count}");
                }

                // 计算总记录数
                var total = roles.Count;

                // 执行分页
                var pagedRoles = roles.Skip((page - 1) * limit).Take(limit).ToList();
                System.Console.WriteLine($"分页后的记录数: {pagedRoles.Count}, 当前页: {page}, 每页显示: {limit}");

                // 构造返回数据
                var data = pagedRoles.Select(r => new
                {
                    id = r.Id,
                    roleName = r.RoleName
                }).ToList();

                System.Console.WriteLine("构造返回数据示例：");
                if (data.Any())
                {
                    System.Console.WriteLine($"第一条记录 - ID: {data[0].id}, 角色名: {data[0].roleName}");
                }

                var result = new
                {
                    code = 0,
                    msg = "",
                    count = total,
                    data = data
                };

                System.Console.WriteLine($"返回数据 - 总数: {total}, 当前页数据量: {data.Count}");
                System.Console.WriteLine("==================== 角色列表请求处理完成 ====================");
                
                return Json(result);
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine("==================== 获取角色列表时发生错误 ====================");
                System.Console.WriteLine($"错误信息: {ex.Message}");
                System.Console.WriteLine($"错误堆栈: {ex.StackTrace}");
                
                return Json(new
                {
                    code = 1,
                    msg = "获取数据失败: " + ex.Message,
                    count = 0,
                    data = new List<object>()
                });
            }
        }

        [HttpPost]
        [IgnoreAntiforgeryToken]
        [Route("/RBAC/CreateRole")]
        public async Task<IActionResult> CreateRole([FromForm] string RoleName)
        {
            try
            {
                System.Console.WriteLine($"接收到创建角色请求 - 角色名称: {RoleName}");
                
                if (string.IsNullOrEmpty(RoleName))
                {
                    return Json(new { success = false, message = "角色名称不能为空" });
                }

                // 检查角色名是否已存在
                var existingRoles = await _roles.GetListAsync();
                if (existingRoles.Any(r => r.RoleName == RoleName))
                {
                    return Json(new { success = false, message = "角色名称已存在" });
                }

                // 创建新角色
                var role = new RoleModel();
                role.RoleName = RoleName;

                var result = await _roles.CreateAsync(role);
                System.Console.WriteLine($"角色创建成功，ID: {result}");
                
                // 返回成功消息
                return Json(new { 
                    success = true, 
                    message = "创建成功",
                    data = new { id = result, roleName = RoleName }
                });
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine($"创建角色时发生错误: {ex.Message}");
                return Json(new { success = false, message = "创建失败：" + ex.Message });
            }
        }

        [HttpPost]
        [IgnoreAntiforgeryToken]
        [Route("/RBAC/UpdateRole")]
        public async Task<IActionResult> UpdateRole([FromForm] int id, [FromForm] string RoleName)
        {
            try
            {
                System.Console.WriteLine($"接收到更新角色请求 - ID: {id}, 角色名称: {RoleName}");
                
                if (string.IsNullOrEmpty(RoleName))
                {
                    return Json(new { success = false, message = "角色名称不能为空" });
                }

                // 检查角色名是否已存在
                var existingRoles = await _roles.GetListAsync();
                if (existingRoles.Any(r => r.RoleName == RoleName && r.Id != id))
                {
                    return Json(new { success = false, message = "角色名称已存在" });
                }

                // 获取要更新的角色
                var role = existingRoles.FirstOrDefault(r => r.Id == id);
                if (role == null)
                {
                    return Json(new { success = false, message = "未找到角色" });
                }

                role.RoleName = RoleName;
                var result = await _roles.UpdateAsync(role);
                System.Console.WriteLine($"角色更新成功，ID: {result}");
                
                // 返回成功消息
                return Json(new { 
                    success = true, 
                    message = "更新成功",
                    data = new { id = result, roleName = RoleName }
                });
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine($"更新角色时发生错误: {ex.Message}");
                return Json(new { success = false, message = "更新失败：" + ex.Message });
            }
        }

        [HttpPost]
        [IgnoreAntiforgeryToken]
        [Route("/RBAC/DeleteRole")]
        public async Task<IActionResult> DeleteRole([FromForm] int id)
        {
            try
            {
                System.Console.WriteLine($"接收到删除角色请求 - ID: {id}");
                
                // 检查角色是否存在
                var existingRoles = await _roles.GetListAsync();
                var role = existingRoles.FirstOrDefault(r => r.Id == id);
                if (role == null)
                {
                    return Json(new { success = false, message = "未找到角色" });
                }

                var result = await _roles.DeleteAsync(id);
                System.Console.WriteLine($"角色删除成功，ID: {result}");
                
                // 返回成功消息
                return Json(new { 
                    success = true, 
                    message = "删除成功",
                    data = new { id = result }
                });
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine($"删除角色时发生错误: {ex.Message}");
                return Json(new { success = false, message = "删除失败：" + ex.Message });
            }
        }
    }
}
